package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.dao.ShoppingCartDao;
import com.itheima.entity.ShoppingCart;
import com.itheima.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;


@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired
    private ShoppingCartDao shoppingCartDao;

    @Override
    public ShoppingCart add(ShoppingCart shoppingCart) {

        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(ShoppingCart::getUserId,shoppingCart.getUserId());


        if(shoppingCart.getDishId() != null){
            //添加到购物车的是菜品
            queryWrapper.eq(ShoppingCart::getDishId,shoppingCart.getDishId());
        }else{
            //添加到购物车的是套餐
            queryWrapper.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        }

        ShoppingCart resultShoppingCart = shoppingCartDao.selectOne(queryWrapper);
        if (resultShoppingCart != null){
            resultShoppingCart.setNumber(resultShoppingCart.getNumber() + 1 ); //设置商品 + 1
            shoppingCartDao.updateById(resultShoppingCart); //更新 记录

        }
        else{
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartDao.update(shoppingCart,queryWrapper);
           resultShoppingCart=shoppingCart;

        }


        return resultShoppingCart;
    }
}
